package com.standardoperationapp.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.standardoperationapp.R;
import com.standardoperationapp.adapter.ApplyListAdapter;
import com.standardoperationapp.adapter.WorkerListAdapter;
import com.standardoperationapp.bean.CilckEventBean;
import com.standardoperationapp.bean.MyAcessDoorBean;

import com.standardoperationapp.bean.StateBean;
import com.standardoperationapp.bean.WorkerBean;
import com.standardoperationapp.global.GlobalVaries;
import com.standardoperationapp.global.GsonUtils;
import com.standardoperationapp.net.BaseSubscribe;
import com.standardoperationapp.net.OnSuccessAndFaultListener;
import com.standardoperationapp.net.OnSuccessAndFaultSub;


import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class ApplyDoorKeyActivity extends AppCompatActivity {

    private TextView titleTv,beginbtn,endbtn;
    private ListView listView,workerListView;
    private RadioGroup radioGroup;
    private Button confirmBtn;
    private EditText reasonET;
    private List<MyAcessDoorBean.DataBean> list = new ArrayList<MyAcessDoorBean.DataBean>();
    private List<WorkerBean.DataBean> workInfolist = new ArrayList<WorkerBean.DataBean>();
    private AlertDialog.Builder alertBuilder;
    private AlertDialog alertDialog;


    private ApplyListAdapter applyListAdapter ;
    private WorkerListAdapter workListAdapter;
    private SelectTimeActivity beginTimeDlg;
    private SelectTimeActivity endTimeDlg;
    private SelectWorkActivity workerDlg;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apply_door_key);
        listView =(ListView) findViewById(R.id.apply_listView);
        workerListView =(ListView) findViewById(R.id.apply_worker_listView);
        reasonET=(EditText)findViewById(R.id.apply_reasonET) ;
        radioGroup=(RadioGroup) findViewById(R.id.rg_aplly_reasonRadioGroup);
        radioGroup.check(R.id.rg_aplly_inRadio);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {

            }
        });
        confirmBtn=(Button)findViewById(R.id.apply_confirmBtn);
        confirmBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(reasonET.getText().toString().isEmpty()){
//                    Dialog alertDialog = new AlertDialog.Builder(ApplyDoorKeyActivity.this).
//                            setTitle("提醒").
//                            setMessage("原因内容不能为空").
//                            create();
//                    alertDialog.show();
                    Toast.makeText(ApplyDoorKeyActivity.this, "申请原因不能为空！" , Toast.LENGTH_LONG).show();
                    return;
                }
                boolean findflag1=false;
                for(int i=0;i<GlobalVaries.idlist.size();i++)
                {
                    if(GlobalVaries.idlist.get(i).getState()==1)
                    {
                        findflag1 =true;
                        break;
                    }
                }
                if(findflag1 ==false)
                {
                    Toast.makeText(ApplyDoorKeyActivity.this, "请选择通道门！" , Toast.LENGTH_LONG).show();
                    return;
                }
                boolean findflag2=false;
                for(int i=0;i<GlobalVaries.worklist.size();i++)
                {
                    if(GlobalVaries.worklist.get(i).getState()==1)
                    {
                        findflag2 =true;
                        break;
                    }
                }
                if(findflag2==false)
                {
                    Toast.makeText(ApplyDoorKeyActivity.this, "请选择申请人员！" , Toast.LENGTH_LONG).show();
                    return;
                }

                DateFormat df = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");
                try {
                    Date dt1 = df.parse(beginbtn.getText().toString());
                    Date dt2 = df.parse(endbtn.getText().toString());
                    if (dt1.getTime() >= dt2.getTime()) {

                        Toast.makeText(ApplyDoorKeyActivity.this, "开始时间不能大于结束时间！" , Toast.LENGTH_LONG).show();
                        return;
                    }
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
                getLockOpenApply();
            }
        });
      //  selectbtn=(Button)findViewById(R.id.apply_selectBtn);
//        selectbtn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//
//                if (alertBuilder == null) {
//                    alertBuilder = new AlertDialog.Builder(ApplyDoorKeyActivity.this);
//                    final View view1 = getLayoutInflater().inflate(R.layout.activity_select_work, null);
//                    worklistView = (ListView) view1.findViewById(R.id.apply_worker_list);
//                    Button closeBtn = (Button) view1.findViewById(R.id.apply_worker_cancel_Btn);
//                    closeBtn.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//
//                         // worklist
//                        }
//                    });
//                    Button okBtn = (Button) view1.findViewById(R.id.apply_worker_ok_Btn);
//                    okBtn.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                            alertDialog.dismiss();
//                            alertBuilder = null;
//                        }
//                    });
//                     initWorkListView();
//                    alertBuilder.setView(view1);
//                 alertDialog = alertBuilder.create();
//
//                    alertDialog.show();
//
//            }
//
//
//            }}
//        );
        initTime();
        initListView();
        initWorkListView();
        getMyAcessDoor();
        getWorerks();

    }
    public void initWorkListView(){

        workerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {


                if( GlobalVaries.worklist.get(i-1).getState() ==0) {

                    GlobalVaries.worklist.get(i-1).setState(1);

                }else{

                    GlobalVaries.worklist.get(i-1).setState(0);

                }
                workListAdapter.notifyDataSetChanged();

            }
        });

        //添加表头
        View headerView1 = LayoutInflater.from(this).inflate(R.layout.applykey_list_item, workerListView, false);
        workerListView.addHeaderView(headerView1);
        TextView tx2= headerView1.findViewById(R.id.apply_txt1);
        tx2.setText("序号");
        tx2= headerView1.findViewById(R.id.apply_txt2);
        tx2.setText("姓名");
        tx2= headerView1.findViewById(R.id.apply_txt3);
        tx2.setVisibility(View.INVISIBLE);
        tx2= headerView1.findViewById(R.id.apply_txt4);
        tx2.setText("操作");

    }
    public void getLockOpenApply(){

        HashMap<String, Object> hashMap= new HashMap<String, Object>();
        //hashMap.put("materialUrl","1111111");
        hashMap.put("leftOpenLockTime", time2str(beginbtn.getText().toString()));
        hashMap.put("rightOpenLockTime", time2str(endbtn.getText().toString()));
        hashMap.put("reason", reasonET.getText().toString());
           List<Integer> stateList = new ArrayList<Integer>();
        for(int i=0;i<GlobalVaries.idlist.size();i++){
            if(GlobalVaries.idlist.get(i).getState()==1)
                stateList.add(list.get(i).getId());
        }
        List<Integer> usrList = new ArrayList<Integer>();
        for(int i=0;i<GlobalVaries.worklist.size();i++){
            if(GlobalVaries.worklist.get(i).getState()==1)
                usrList.add(workInfolist.get(i).getUserId());
        }
        hashMap.put("doorIds",stateList);
        hashMap.put("userIds",usrList);
        BaseSubscribe.getLockOpenKey(ApplyDoorKeyActivity.this,hashMap, new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
            @Override
            public void onSuccess(Object result) {
//                ApplyKeyBean myAcessDoorBean = GsonUtils.fromJson(result.toString(), ApplyKeyBean.class);
//                for (int i = 0; i < myAcessDoorBean.getArray().size(); i++) {
//                    MyAcessDoorBean.DataBean dataItem = myAcessDoorBean.getArray().get(i);
//                    list.add(dataItem);
//                    idlist.add(new StateBean(dataItem.getId(),0));
//                }
//                if (applyListAdapter == null) {
//                    applyListAdapter = new ApplyListAdapter(ApplyDoorKeyActivity.this, list);
//                    listView.setAdapter(applyListAdapter);
//                } else {
//                    applyListAdapter.upDta(list);
//                    applyListAdapter.notifyDataSetChanged();
//                }
                Toast.makeText(ApplyDoorKeyActivity.this, "申请开门钥匙成功，请等待审核！" , Toast.LENGTH_LONG).show();
 Intent intent = new Intent(ApplyDoorKeyActivity.this, BluetoothSetActivity.class);
 startActivity(intent);

            }

            @Override
            public void onFault(String errorMsg) {
                Toast.makeText(ApplyDoorKeyActivity.this, "获取开门钥匙失败！" + errorMsg, Toast.LENGTH_LONG).show();
            }

        }));


    }
    //获取当前部门下通道门信息列表
    public void getMyAcessDoor(){

        BaseSubscribe.getMyAccessDoor(ApplyDoorKeyActivity.this, new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
            @Override
            public void onSuccess(Object result) {
                MyAcessDoorBean myAcessDoorBean = GsonUtils.fromJson(result.toString(), MyAcessDoorBean.class);
                GlobalVaries.idlist.clear();
                if(myAcessDoorBean==null){
                    Toast.makeText(ApplyDoorKeyActivity.this, "后台发送通道锁列表为空！" , Toast.LENGTH_LONG).show();

                    return;
                }
                for (int i = 0; i < myAcessDoorBean.getData().size(); i++) {
                    MyAcessDoorBean.DataBean dataItem = myAcessDoorBean.getData().get(i);
                    if(dataItem==null){
                        continue;
                    }
                    list.add(dataItem);
                    GlobalVaries.idlist.add(new StateBean(i,0));
                }
                if (applyListAdapter == null) {
                    applyListAdapter = new ApplyListAdapter(ApplyDoorKeyActivity.this, list);
                    listView.setAdapter(applyListAdapter);
                } else {
                    applyListAdapter.upDta(list);
                    applyListAdapter.notifyDataSetChanged();
                }

            }

            @Override
            public void onFault(String errorMsg) {
                Toast.makeText(ApplyDoorKeyActivity.this, "获取通道锁列表失败！" + errorMsg, Toast.LENGTH_LONG).show();
            }

        }));


    }
    public void getWorerks(){

        BaseSubscribe.getDropList(ApplyDoorKeyActivity.this, new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
            @Override
            public void onSuccess(Object result) {
                WorkerBean workerBean = GsonUtils.fromJson(result.toString(), WorkerBean.class);
                if(workerBean==null)
                {
                    Toast.makeText(ApplyDoorKeyActivity.this, "后台发送人员信息为空！" , Toast.LENGTH_LONG).show();
                    return;
                }
                GlobalVaries.worklist.clear();
                for (int i = 0; i < workerBean.getData().size(); i++) {
                    WorkerBean.DataBean  dataItem = workerBean.getData().get(i);
                    if(dataItem==null)
                    {
                        continue;
                    }
                    workInfolist.add(dataItem);
                    GlobalVaries.worklist.add(new StateBean(i,0));
                }
                if (workListAdapter == null) {
                    workListAdapter = new WorkerListAdapter(ApplyDoorKeyActivity.this, workInfolist);
                    workerListView.setAdapter(workListAdapter);
                } else {
                    workListAdapter.upDta(workInfolist);
                    workListAdapter.notifyDataSetChanged();
                }

            }

            @Override
            public void onFault(String errorMsg) {
                Toast.makeText(ApplyDoorKeyActivity.this, "获取人员信息失败！" + errorMsg, Toast.LENGTH_LONG).show();
            }

        }));


    }
    private void initListView()
    {
        listView=(ListView)findViewById(R.id.apply_listView) ;

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Log.e("syj","list  CLICK1 "+Integer.toString(i));
//                View itemLayout = view;
//                TextView tx =itemLayout.findViewById(R.id.apply_txt3);
//                MyAcessDoorBean.DataBean item= (MyAcessDoorBean.DataBean)listView.getAdapter().getItem(i-1);

//               cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//                   @Override
//                   public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                       if(cb.isChecked())
//                       {
               if( GlobalVaries.idlist.get(i-1).getState() ==0) {
                   Log.e("syj", "CLICK-2 ");
                   GlobalVaries.idlist.get(i-1).setState(1);
                 //  tx.setBackgroundResource(R.drawable.wish_select_on_icon);
               }else{
                   Log.e("syj","CLICK-3 ");
                   GlobalVaries.idlist.get(i-1).setState(0);
               //    tx.setBackgroundResource(R.drawable.wish_select_off_icon);
               }
               applyListAdapter.notifyDataSetChanged();
//                       }else if(!cb.isChecked())
//                       {
//                           Log.e("syj","CLICK-3 ");
//                           idlist.get(i).setState(0);
//                       }
//                   }
         //      });
            }
        });
        //添加表头
        View headerView = LayoutInflater.from(this).inflate(R.layout.applykey_list_item, listView, false);
        listView.addHeaderView(headerView);
        TextView tx1= headerView.findViewById(R.id.apply_txt1);
        tx1.setText("序号");
        tx1= headerView.findViewById(R.id.apply_txt2);
        tx1.setText("通道门");
        tx1= headerView.findViewById(R.id.apply_txt3);
        tx1.setVisibility(View.INVISIBLE);
        tx1= headerView.findViewById(R.id.apply_txt4);
        tx1.setText("操作");


    }
public String time2str (String tstr)
{
    String re =tstr;
    String result = tstr.replace("年","-");
    result = result.replace("月","-");
    result = result.replace("日","");
    re=result;
    return re;
}
    public void initTime()
    {
        SimpleDateFormat sdfBegin = new SimpleDateFormat("yyyy年MM月dd日 00:00");
        String beginTm = sdfBegin.format(new java.util.Date());

        beginbtn=(TextView) findViewById(R.id.apply_beginTime);
        beginbtn.setText(beginTm+":00");
        beginTimeDlg = new SelectTimeActivity(ApplyDoorKeyActivity.this, beginTm, true);
        beginbtn.setOnClickListener(new View.OnClickListener(){

            @Override
            public void  onClick(View v)
            {
                beginTimeDlg.finish();
                //endTimeDlg.finish();
                beginTimeDlg.setDateTime(beginbtn.getText().toString());
                beginTimeDlg.dateTimePicKDialog(beginbtn);
            }

        });
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 23:59");
        String curTm = sdf.format(new java.util.Date());
        endbtn=(TextView)findViewById(R.id.apply_endTime);
        endbtn.setText(curTm+":59");
        endTimeDlg = new SelectTimeActivity(ApplyDoorKeyActivity.this, curTm, true);
        endbtn.setOnClickListener(new View.OnClickListener(){

            @Override
            public void  onClick(View v)
            {
                endTimeDlg.finish();
                //endTimeDlg.finish();
                endTimeDlg.setDateTime(endbtn.getText().toString());
                endTimeDlg.dateTimePicKDialog(endbtn);
            }

        });


    }
}